package labox.innovation.gameserver.model.quest;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import labox.innovation.config.Config;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;
import labox.innovation.gameserver.timer.Timer;

import javolution.util.FastList;

public class QuestStateManager {
	protected static final Logger _log = LoggerFactory.getLogger(QuestStateManager.class.getName());

	// =========================================================
	// Data Field
	private List<QuestState> _questStates = new FastList<QuestState>();

	// =========================================================
	// Constructor
	private QuestStateManager() {
		new Timer(60000,true,
		new Runnable(){
			public void run(){
				try {
					cleanUp();
				} catch (Exception e) {
					_log.error("Quest State Manager", Config.SERVER_ID, e);
				}
			}
		}
		).start();
	}

	// =========================================================
	// Method - Public
	/**
	 * Add QuestState for the specified player instance
	 */
	public void addQuestState(Quest quest, FuzePcInstance player, byte state) {
		QuestState qs = getQuestState(player);
		if (qs == null)
			qs = new QuestState(quest, player, state);
	}

	/**
	 * Remove all QuestState for all player instance that does not exist
	 */
	public void cleanUp() {
		for (int i = getQuestStates().size() - 1; i >= 0; i--) {
			if (getQuestStates().get(i).getPlayer() == null) {
				removeQuestState(getQuestStates().get(i));
				getQuestStates().remove(i);
			}
		}
	}

	// =========================================================
	// Method - Private
	/**
	 * Remove QuestState instance
	 */
	private void removeQuestState(QuestState qs) {
		qs = null;
	}

	// =========================================================
	// Property - Public
	public static final QuestStateManager getInstance() {
		return SingletonHolder._instance;
	}

	/**
	 * Return QuestState for specified player instance
	 */
	public QuestState getQuestState(FuzePcInstance player) {
		for (QuestState q : getQuestStates()) {
			if (q.getPlayer() != null && q.getPlayer().getObjectId() == player.getObjectId())
				return q;
		}

		return null;
	}

	/**
	 * Return all QuestState
	 */
	public List<QuestState> getQuestStates() {
		if (_questStates == null)
			_questStates = new FastList<QuestState>();
		return _questStates;
	}

	@SuppressWarnings("synthetic-access")
	private static class SingletonHolder {
		protected static final QuestStateManager _instance = new QuestStateManager();
	}
}
